package com.yc.home.cloudother.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.bean.Result;
import com.yc.entity.Doquestion;
import com.yc.entity.Question;
import com.yc.home.cloudother.mapper.DoquestionMapper;
import com.yc.home.cloudother.mapper.QuestionMapper;
import com.yc.home.cloudother.service.IDoquestionService;
import com.yc.home.cloudother.service.IMakenoService;
import com.yc.home.cloudother.service.IQuestionService;
import com.yc.home.cloudother.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lzk
 * @since 2024-09-23
 */
@RestController
@RequestMapping("/question")
public class QuestionController {
    
    @Autowired
    IQuestionService iQuestionService;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    DoquestionMapper doquestionMapper;

    //获取数量
    @RequestMapping("questionNum")
    Result questionNum(String id, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(0, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(0, "无效的JWT令牌", null);
        }
        Object nid = user.get("id");
        String uid = nid.toString();
        //总数
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Question::getCourse, id);
        lqw.eq(Question::getStatus, 1);
        Long aLong = questionMapper.selectCount(lqw);
        //刷题
        LambdaQueryWrapper<Doquestion> lqw1 = new LambdaQueryWrapper<>();
        lqw1.eq(Doquestion::getUid, uid);
        lqw1.eq(Doquestion::getTid, id);
        Long aLong1 = doquestionMapper.selectCount(lqw1);
        HashMap data = new HashMap<>();
        data.put("all", aLong);
        data.put("do", aLong1);
        return new Result(1, "数量", data);
    }

    @RequestMapping("queryQuestion")
    Result queryQuestion(@RequestParam(defaultValue = "1") int page,
                         @RequestParam(defaultValue = "10") int size, String type, String input, String id, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(0, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(0, "无效的JWT令牌", null);
        }
        Object nid = user.get("id");
        String uid = nid.toString();
        Page pageObj = null;
        //三种状态  全部  已做题   未做题
        if("全部".equals(type)){
            //获取全部
            pageObj = iQuestionService.getAll(page, size, input, id);
        }
        if("已刷题".equals(type)){
            //获取已做题
            pageObj = iQuestionService.getYes(page, size, input, id, uid);
        }
        if("未刷题".equals(type)){
            //获取未做题
            pageObj = iQuestionService.getNo(page, size, input, id, uid);
        }
        return new Result(1, "题目", pageObj);
    }

    //获取题目
    @RequestMapping("queryAll")
    Result queryAll(String input){
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        lqw.like(Question::getContent, "%" + input + "%");
        lqw.eq(Question::getStatus, 1);
        List<Question> questions = questionMapper.selectList(lqw);
        return new Result(1, "题目数据", questions);
    }

    //获取未做题
    @RequestMapping("queryno")
    Result queryno(String id, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(0, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(0, "无效的JWT令牌", null);
        }
        Object nid = user.get("id");
        String uid = nid.toString();
        List<Question> questions = null;
        // 条件设置
        LambdaQueryWrapper<Doquestion> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Doquestion::getTid, id);     //类别id
        lqw.eq(Doquestion::getUid, uid);    //用户id
        //查出所有刷题的
        List<Doquestion> doquestions = doquestionMapper.selectList(lqw);
        //获取所有的刷题id
        List<Object> collect = doquestions.stream().map(Doquestion::getQid).collect(Collectors.toList());
        //创建查询条件
        LambdaQueryWrapper<Question> lqw1 = new LambdaQueryWrapper<>();
        //判断刷题有没有记录
        if(!collect.isEmpty()){
            //有记录查询所有未刷题
            lqw1.notIn(Question::getId, collect);
            lqw1.eq(Question::getCourse, id);
            lqw1.eq(Question::getStatus, 1);
            // 执行分页查询
            questions = questionMapper.selectList(lqw1);

            //并且通过查询刷题记录，将错题也加入到刷题里面
            LambdaQueryWrapper<Doquestion> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(Doquestion::getTid, id)
                    .gt(Doquestion::getStatus, 0)  // 添加这个条件来确保status大于0
                    .orderByDesc(Doquestion::getStatus)
                    .last("limit 1");
            List<Doquestion> doquestions1 = doquestionMapper.selectList(lqw2);

            if(doquestions1.size() > 0){
                LambdaQueryWrapper<Doquestion> lqw3 = new LambdaQueryWrapper<>();
                lqw3.eq(Doquestion::getTid, id).eq(Doquestion::getStatus, doquestions1.get(0).getStatus());
                List<Doquestion> doquestions2 = doquestionMapper.selectList(lqw3);

                List<Question> questionList = new ArrayList<>();
                for (int i = 0; i < doquestions2.size(); i++) {
                    Question question = questionMapper.selectById(doquestions2.get(i).getQid());
                    questionList.add(question);
                }
                questionList.addAll(questions);
                return new Result(1, "题目", questionList);
            }else{
                return new Result(1, "题目", questions);
            }
        }else{
            //没有记录，查出所有题目为未刷题
            lqw1.eq(Question::getCourse, id);
            lqw1.eq(Question::getStatus, 1);
            questions = questionMapper.selectList(lqw1);
            return new Result(1, "题目", questions);
        }
    }

    @Autowired
    IDoquestionService iDoquestionService;

    @Autowired
    IMakenoService iMakenoService;

    //判断题目对错
    @RequestMapping("confirm")
    Result confirm(String answer, String qid, String tid, @RequestHeader(name = "Authorization") String jwt){
        Claims user;
        try {
            user = JwtUtil.parseJWT(jwt);
            // 检查JWT是否过期
            if (JwtUtil.isTokenExpired(user.getExpiration())) { // 假设JwtUtil有这样一个方法
                return new Result(-2, "JWT已过期", null);
            }
        } catch (Exception e) {
            // 解析JWT时发生的异常，可能表示JWT格式错误或已损坏
            return new Result(-2, "无效的JWT令牌", null);
        }
        Object nid = user.get("id");
        String uid = nid.toString();
        try{
            //判断题目对错
            Result pd = iQuestionService.pd(answer, qid);
            //对的就添加刷题表
            if(pd.getCode() == 1){
                iDoquestionService.add(uid, qid, tid, answer);
            }
            //错的就添加刷题表，添加错题集
            if(pd.getCode() == 0 || pd.getCode() == 2){
                iDoquestionService.addno(uid, qid, tid, answer);
                //插入错题集
                iMakenoService.add(uid, qid, tid, answer);
            }
            return pd;
        }catch (Exception e){
            return new Result(-1, "系统错误，请稍后再试", null);
        }
    }

    //查询题目
    @RequestMapping("query")
    public Page<Question> query(Question question,
                                @RequestParam(defaultValue = "1") int page,
                                @RequestParam(defaultValue = "15") int size){
        // 创建分页对象
        Page<Question> pageObj = new Page<>(page, size);

        // 条件设置
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();

        // 类别判断
        if (question.getType() != null && !question.getType().isBlank()) {
            lqw.eq(Question::getType, question.getType());
        }

        // 课程设置
        if (question.getCourse() != null && !question.getCourse().isBlank()) {
            lqw.eq(Question::getCourse, question.getCourse());
        }

        lqw.eq(Question::getStatus, 1);

        // 执行分页查询
        return questionMapper.selectPage(pageObj, lqw);
    }

    //获取全部题目
    @RequestMapping("get")
    public Result get(String tid){
        List<Question> questions;
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Question::getStatus, 1);
        if(!"".equals(tid)){
            lqw.eq(Question::getCourse, tid);
            questions = questionMapper.selectList(lqw);
        }else{
            questions = questionMapper.selectList(null);
        }
        return new Result(1, "题目", questions);
    }

    //后台获取题目
    @RequestMapping("bygoods")
    Page bygoods(@RequestParam(defaultValue = "1") int currentPage4, @RequestParam(defaultValue = "10") int pagesize, String pid, String pname, String tid, String status, String types){
        Page<Question> page = new Page<>(currentPage4, pagesize);
        LambdaQueryWrapper<Question> lqw = new LambdaQueryWrapper<>();
        if(!"".equals(pid)){
            lqw.eq(Question::getId, pid);
        }
        if(!"".equals(pname)){
            lqw.like(Question::getContent, pname);
        }
        if(!"".equals(tid)){
            lqw.eq(Question::getCourse, tid);
        }
        if(!"-1".equals(status)){
            lqw.eq(Question::getStatus, status);
        }
        if(!"-1".equals(types)){
            lqw.eq(Question::getType, types);
        }
        return questionMapper.selectPage(page, lqw);
    }

    @RequestMapping("banL")
    Result banL(String id, String status){
        Question question = questionMapper.selectById(id);
        if("0".equals(status)) {
            question.setStatus(1);
        }
        if("1".equals(status)) {
            question.setStatus(0);
        }
        questionMapper.updateById(question);
        return new Result(1, "成功", null);
    }

    @RequestMapping("addQuestion")
    public Result addQuestion(@RequestBody @Valid Question question, Errors errors){
        //选项选择字段判断
        if(question.getType().endsWith("选题")){
            int sum = 0;
            for (String s : question.getItems().split(";")) {
                if(s.startsWith("$")){
                    sum = sum + 1;
                }
            }
            if (sum == 0) {
                errors.rejectValue("items", "no", "请选择选项!");
            }

            if("单选题".equals(question.getType()) && sum > 1){
                errors.rejectValue("items", "no", "单选题只能一个选项!");
            }

            //不能填空值选项
            String[] split = question.getItems().split(";");
            for (String item : split) {
                // 使用 trim() 方法移除字符串前后的空格，并检查是否为空
                if (item.trim().isEmpty()) {
                    // 如果发现空字符串或仅包含空格的字符串，则退出方法或执行其他操作
                    errors.rejectValue("items", "no", "选项不能设置空!");
                    break;
                }
            }
        }

        //字段判断
        if (errors.hasErrors()) {
            return new Result(0, "有信息为空！", errors.getAllErrors());
        }

        if("判断题".equals(question.getType())){
            if(question.getItems().contains("true")){
                question.setItems("true");
            }else{
                question.setItems("false");
            }
        }

        //存入题目
        try{
            question.setStatus(1);
            questionMapper.insert(question);
            return new Result(1, "上传成功", null);
        }catch (Exception e){
            return new Result(-1, "系统异常", null);
        }
    }

    @Transactional
    @RequestMapping("update")
    public Result update(@RequestBody @Valid Question question, Errors errors){
        //选项选择字段判断
        if(question.getType().endsWith("选题")){
            int sum = 0;
            for (String s : question.getItems().split(";")) {
                if(s.startsWith("$")){
                    sum = sum + 1;
                }
            }
            if (sum == 0) {
                errors.rejectValue("items", "no", "请选择选项!");
            }

            if("单选题".equals(question.getType()) && sum > 1){
                errors.rejectValue("items", "no", "单选题只能一个选项!");
            }
        }

        //字段判断
        if (errors.hasErrors()) {
            return new Result(0, "有信息为空！", errors.getAllErrors());
        }
        //存入题目
        try{
            questionMapper.updateById(question);
            return new Result(1, "修改成功", null);
        }catch (Exception e){
            return new Result(-1, "系统异常", null);
        }
    }

    @RequestMapping("getbyid")
    Result getbyid(String id){
        Question question = questionMapper.selectById(id);
        return new Result(1, "题目详情", question);
    }

}

